package controllers;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import models.User;
import system.App;
import system.Controller;
import system.Helper;
import system.MailServer;

/**
 *
 * @author Rezan Achmad
 */
@WebServlet(name = "RegisterController", urlPatterns = {"/register", "/register/", "/register/info"})
public class RegisterController extends Controller {

    @Override
    protected void initRules() {
        rules.put("/register", identity.isGuest());
        rules.put("/register/", identity.isGuest());
        rules.put("/register/info", identity.isGuest());
    }
    
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userPath = request.getServletPath();
        if (userPath.equals("/register") || userPath.equals("/register/")) {
            userPath += "/register";
            if (isGet) {
                if (request.getParameter("activate") != null) {

                    activateAction(request, response);
                    String messageInfo = "Your account has been activated! Please login to start browsing the site.";
                    request.setAttribute("messageInfo", messageInfo);
                    userPath = request.getServletPath() + "/info";

                    setView("/register/info", request, response);
                } else {
                    setView(userPath, request, response);
                }
            } else if (isPost) {
                String messageInfo;
                if (registerAction(request, response)) {
                    messageInfo = "Thank you for your registration. Check your email to activate your account.";
                } else {
                    messageInfo = "Sorry. Your email address has been used by another user. Try another email address";
                }
                request.setAttribute("messageInfo", messageInfo);
                userPath = request.getServletPath() + "/info";

                setView("/register/info", request, response);
            } else {
                setView(userPath, request, response);
            }
        } else if (userPath.equals("/register/info") || userPath.equals("/register/info/")) {
            setView("/register/info", request, response);
        }
    }

    private boolean registerAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Create user
        User user = new User();
        user.nama_lengkap = request.getParameter("fullname");
        user.nama_panggilan = request.getParameter("shortname");
        user.email = request.getParameter("email");
        user.no_telepon = request.getParameter("telephone");
        user.alamat = request.getParameter("address");
        user.is_registered = 0;

        //Generate Random Password :
        String password = Helper.GenerateRandomString();
        App.log(password);
        System.out.println(password);
        user.password = Helper.MD5(password);

        //Add user
        boolean statusAdd = user.add();
        System.out.println("status add user ke database"+statusAdd);
        if (statusAdd) {
            //Send Email :
            System.out.println("user.add true");
            String to[] = new String[]{user.email};
            String subject = "Registration";
            String linkRegistration = Helper.getBaseUrl(request) + "/register?activate=" + user.email;
            String message = "Dear " + user.nama_lengkap + ",\nThank you for your registration. Your account will be activated after clicking this link: " + linkRegistration + "\n\nYour account info :\nUsername : " + user.email + "\nPassword : " + password;
            
            MailServer.sendEmail(to, subject, message);
            
            return true;
        } else {
            System.out.println("user.add false");
            return false;
        }


    }

    private void activateAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Activate User :
        String email = request.getParameter("activate");

        //Update User :
        User user = new User();
        user.email = email;
        System.out.println(email + "AAAAAAAAAAAAAAAAAAA");
        user.activate();
    }
}
